package com.ljx.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.Domain.Dish;
import com.ljx.Domain.DishFlavor;
import com.ljx.Dto.DishDto;
import com.ljx.Mapper.DishMapper;
import com.ljx.Service.DishFlavorService;
import com.ljx.Service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    DishFlavorService dishFlavorService;

    /**
     * 添加菜品
     * @param dishDto
     */
    @Override
    @Transactional
    public void addDish(DishDto dishDto) {
        //将一部分数据保存到dish里面
       this.save(dishDto);
        Long id = dishDto.getId();
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //使用stream()流保存dishId
        flavors= flavors.stream().map((item)->{
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdDish(Long id) {
        //根据id查询dish表
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        //根据categoryId查询数据
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加条件根据categoryId查询数据
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
        //补充数据到dishDto
        dishDto.setFlavors(dishFlavorList);

        return dishDto;
    }

    /**
     * 修改菜品
     * @param dishDto
     */
    @Override
    @Transactional
    public void updateDish(DishDto dishDto) {

        //根据id修改dish中的数据
        this.updateById(dishDto);
       //根据id删除dishFlavor中的数据
        //添加条件构造器
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        //添加删除条件
        wrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);
        //根据id添加dishFlavor数据
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //使用stream()流保存dishId
        flavors= flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }
}
